package org.jeecg.modules.business.doc.outbound.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.mapper.BasicMaterialMapper;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceipt;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceiptMaterial;
import org.jeecg.modules.business.doc.outbound.entity.dto.ListByOutboundIdResponseVO;
import org.jeecg.modules.business.doc.outbound.entity.vo.*;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptMaterialService;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptService;
import org.jeecg.modules.business.doc.outbound.vo.WmsOutReceiptMaterialResponseVO;
import org.jeecg.modules.business.doc.outbound.vo.WmsOutReceiptPage;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterialExport;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * @Description: 出库单
 * @Author: jeecg-boot
 * @Date: 2023-08-09
 * @Version: V1.0
 */
@Api(tags = "出库单")
@RestController
@RequestMapping("/business/wmsOutReceipt")
@Slf4j
public class WmsOutReceiptController {
    @Autowired
    private IWmsOutReceiptService wmsOutReceiptService;
    @Autowired
    private IWmsOutReceiptMaterialService wmsOutReceiptMaterialService;
    @Autowired
    private BasicMaterialMapper basicMaterialMapper;
    @Autowired
    private IWmsOutReceiptTaskService iWmsOutReceiptTaskService;

    /**
     * 出库单提交
     *
     * @param id
     * @param req
     * @return
     */
    @ApiOperation(value = "出库单提交", notes = "出库单提交")
    @PostMapping("/commit")
    public Result<Void> commit(@RequestParam("id") String id,
                               HttpServletRequest req) {
        wmsOutReceiptService.commit(id, req);
        return Result.ok();
    }

    @ApiOperation(value = "出库单下查", notes = "出库单下查")
    @GetMapping(value = "/listWmsOutReceipt")
    public Result<List<WmsOutReceipt>> listWmsOutReceipt(@RequestParam("wmsOutReceiptTaskId") String wmsOutReceiptTaskId) {

        List<WmsOutReceipt> wmsOutReceiptList = wmsOutReceiptService.listWmsOutReceipt(wmsOutReceiptTaskId);
        return Result.ok(wmsOutReceiptList);
    }

    /**
     * 通过出库任务id查询出库任务物料对应出库单物料相同字段
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过出库任务id查询出库任务物料对应出库单物料相同字段", notes = "通过出库任务id查询出库任务物料对应出库单物料相同字段")
    @GetMapping(value = "/listByOutboundTaskId")
    public Result<List<ListByOutboundIdResponseVO>> listByOutboundTaskId(@RequestParam("id") String id) {
        List<ListByOutboundIdResponseVO> list = wmsOutReceiptService.listByOutboundTaskId(id);
        return Result.ok(list);
    }

    /**
     * 分页列表查询
     *
     * @param wmsOutReceipt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "出库单-分页列表查询")
    @ApiOperation(value = "出库单-分页列表查询", notes = "出库单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmsOutReceiptPageVO>> queryPageList(WmsOutReceiptQueryVO wmsOutReceipt,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<WmsOutReceipt> page = new Page<>(pageNo, pageSize);
        IPage<WmsOutReceiptPageVO> pageList = wmsOutReceiptService.listByPage(page, wmsOutReceipt);
        List<WmsOutReceiptPageVO> records = pageList.getRecords();
        List<String> ids = records.stream().map(WmsOutReceipt::getId).collect(Collectors.toList());
        List<WmsOutReceiptMaterial> list = wmsOutReceiptMaterialService.list(new LambdaQueryWrapper<WmsOutReceiptMaterial>()
                .in(CollectionUtil.isNotEmpty(ids), WmsOutReceiptMaterial::getWmsOutReceiptId, ids));
        records.forEach(o -> {
            if (list.stream().filter(x -> x.getWmsOutReceiptId().equals(o.getId())).count() > 0) {
                o.setHasChild(1);
            } else {
                o.setHasChild(0);
            }
            //设置过账标识
            if(TransferStatusEnum.TRANSFER_FAIL.getCode().equals(o.getTransferSapStatus())){
                o.setTransferButton(true);
            }else{
                o.setTransferButton(false);
            }
        });
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmsOutReceiptPage
     * @return
     */
    @AutoLog(value = "出库单-添加")
    @ApiOperation(value = "出库单-添加", notes = "出库单-添加")
    @RequiresPermissions("doc:wms_out_receipt:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmsOutReceiptPage wmsOutReceiptPage) {
        WmsOutReceipt wmsOutReceipt = new WmsOutReceipt();
        BeanUtils.copyProperties(wmsOutReceiptPage, wmsOutReceipt);
        String s = wmsOutReceiptService.saveMain(wmsOutReceipt, wmsOutReceiptPage.getWmsOutReceiptMaterialList(), false);
        return Result.OK("新增成功！", s);
    }

    /**
     * 编辑
     *
     * @param wmsOutReceiptPage
     * @return
     */
    @AutoLog(value = "出库单-编辑")
    @ApiOperation(value = "出库单-编辑", notes = "出库单-编辑")
    @RequiresPermissions("doc:wms_out_receipt:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmsOutReceiptPage wmsOutReceiptPage) {
        WmsOutReceipt wmsOutReceipt = new WmsOutReceipt();
        BeanUtils.copyProperties(wmsOutReceiptPage, wmsOutReceipt);
        WmsOutReceipt wmsOutReceiptEntity = wmsOutReceiptService.getById(wmsOutReceipt.getId());
        if (wmsOutReceiptEntity == null) {
            return Result.error("未找到对应数据");
        }
        wmsOutReceiptService.updateMain(wmsOutReceipt, wmsOutReceiptPage.getWmsOutReceiptMaterialList(), false);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单-通过id删除")
    @ApiOperation(value = "出库单-通过id删除", notes = "出库单-通过id删除")
    @RequiresPermissions("doc:wms_out_receipt:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmsOutReceiptService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出库单-批量删除")
    @ApiOperation(value = "出库单-批量删除", notes = "出库单-批量删除")
    @RequiresPermissions("doc:wms_out_receipt:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmsOutReceiptService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "出库单-通过id查询")
    @ApiOperation(value = "出库单-通过id查询", notes = "出库单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmsOutReceipt> queryById(@RequestParam(name = "id", required = true) String id) {
        WmsOutReceipt wmsOutReceipt = wmsOutReceiptService.getById(id);
        if (wmsOutReceipt == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmsOutReceipt);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "出库单-物料通过主表ID查询")
    @ApiOperation(value = "出库单-物料主表ID查询", notes = "出库单-物料-通主表ID查询")
    @GetMapping(value = "/queryWmsOutReceiptMaterialByMainId")
    public Result<List<WmsOutReceiptMaterialResponseVO>> queryWmsOutReceiptMaterialListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<WmsOutReceiptMaterial> list = wmsOutReceiptMaterialService.selectByMainId(id);
        List<WmsOutReceiptMaterialResponseVO> result = BeanUtil.copyToList(list, WmsOutReceiptMaterialResponseVO.class);
        List<String> materialIds = list.stream().map(WmsOutReceiptMaterial::getWmsBasicMaterialId).collect(Collectors.toList());
        List<BasicMaterial> basicMaterials = basicMaterialMapper.selectList(new LambdaQueryWrapper<BasicMaterial>()
                .in(CollectionUtil.isNotEmpty(materialIds), BasicMaterial::getId, materialIds));
        WmsOutReceipt wmsOutReceipt = wmsOutReceiptService.getById(id);
        for (WmsOutReceiptMaterialResponseVO vo : result) {
            basicMaterials.forEach(o -> {
                if (o.getId().equals(vo.getWmsBasicMaterialId())) {
                    vo.setMaterialName(o.getName());
                    vo.setMaterialCode(o.getCode());
                    vo.setSpecification(o.getSpecification());
                    if(!Objects.isNull(wmsOutReceipt)){
                        vo.setOutDate(wmsOutReceipt.getOutDate());
                    }
                }
            });
        }

        return Result.OK(result);
    }
    /**
     * 通过id分页查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "出库单-物料主表ID分页查询", notes = "出库单-物料-通主表ID分页查询")
    @GetMapping(value = "/queryPageReceiptMaterialByTaskId")
    public Result<IPage<WmsOutReceiptMaterialResponseVO>> queryPageReceiptMaterialByTaskId(@RequestParam(name = "id") String id,
                                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        IPage<WmsOutReceiptMaterial> page = new Page<>(pageNo, pageSize);
        IPage<WmsOutReceiptMaterialResponseVO> pageList=wmsOutReceiptMaterialService.queryPageReceiptMaterialByTaskId(page,id);
        return Result.OK(pageList);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param wmsOutReceipt
     */
    @ApiOperation(value = "出库单-导出excel", notes = "出库单-导出excel")
    @RequiresPermissions("doc:wms_out_receipt:exportXls")
    @PostMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsOutReceipt wmsOutReceipt) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<WmsOutReceipt> queryWrapper = QueryGenerator.initQueryWrapper(wmsOutReceipt, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<WmsOutReceipt> wmsOutReceiptList = wmsOutReceiptService.list(queryWrapper);
        List<String> receiptIds = wmsOutReceiptList.stream().map(w -> w.getId()).collect(Collectors.toList());
        List<WmsOutReceiptMaterial> outReceiptMaterials = wmsOutReceiptMaterialService.list(
                new LambdaQueryWrapper<WmsOutReceiptMaterial>()
                        .in(WmsOutReceiptMaterial::getWmsOutReceiptId,receiptIds));
        Map<String, List<WmsOutReceiptMaterial>> listMap = new HashMap<>();
        if(outReceiptMaterials != null ){
            listMap = outReceiptMaterials.stream()
                    .collect(Collectors.groupingBy(WmsOutReceiptMaterial::getWmsOutReceiptId));
        }

        // Step.3 组装pageList
        List<WmsOutReceiptPage> pageList = new ArrayList<WmsOutReceiptPage>();
        for (WmsOutReceipt main : wmsOutReceiptList) {
            WmsOutReceiptPage vo = new WmsOutReceiptPage();
            BeanUtils.copyProperties(main, vo);
            List<WmsOutReceiptMaterial> wmsOutReceiptMaterialList = listMap.getOrDefault(main.getId(),new ArrayList<>());
            vo.setWmsOutReceiptMaterialList(wmsOutReceiptMaterialList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出库单列表");
        mv.addObject(NormalExcelConstants.CLASS, WmsOutReceiptPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单数据", "导出人:" + sysUser.getRealname(), "出库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("doc:wms_out_receipt:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<WmsOutReceiptPage> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsOutReceiptPage.class, params);
                for (WmsOutReceiptPage page : list) {
                    WmsOutReceipt po = new WmsOutReceipt();
                    BeanUtils.copyProperties(page, po);
                    wmsOutReceiptService.saveMain(po, page.getWmsOutReceiptMaterialList(), false);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 选单-查询所有未创建出库单的物料信息
     * @return
     */
    @ApiOperation(value = "选单-查询所有未创建出库单的物料信息", notes = "选单-查询所有未创建出库单的物料信息")
    @PostMapping(value = "/listAllUnCreate")
    public Result<List<UnCreateOutVO>> listAllUnCreate(@Valid @RequestBody UnCreateReqVO unCreateReqVO){

        List<UnCreateOutVO> list=wmsOutReceiptService.listAllUnCreate(unCreateReqVO);
        return Result.OK(list);
    }

    /**
     * 选单-查询出库单需要的物料信息
     * @param materialIdList
     * @return
     */
    @ApiOperation(value = "选单-查询出库单需要的物料信息", notes = "选单-查询出库单需要的物料信息")
    @PostMapping(value = "/getUnCreateMaterials")
    public Result<List<WmsOutReceiptMaterialResponseVO>> getUnCreateMaterials(@RequestBody List<String> materialIdList){
        List<WmsOutReceiptMaterialResponseVO> list=wmsOutReceiptService.getUnCreateMaterials(materialIdList);
        return Result.ok(list);
    }


    /**
     * 补单-新增物料
     * @return
     */
    @Deprecated
    @ApiOperation(value = "补单-新增物料", notes = "补单-新增物料")
    @PostMapping(value = "/addReceiptMaterial")
    public Result<Void> addReceiptMaterial(@Valid @RequestBody UnCreateAddVO unCreateAddVO){
        wmsOutReceiptService.addReceiptMaterial(unCreateAddVO);
        return Result.ok();
    }

    /**
     * 盘亏单过账
     * @return
     */
    @Deprecated
    @ApiOperation(value = "盘亏单过账", notes = "盘亏单过账")
    @GetMapping(value = "/pkdPassSAP")
    public Result<Void> pkdPassSAP(String id){
        return wmsOutReceiptService.pkdPassSAP(id);
    }

}
